package com.lnold.redis.config.controller;
import com.lnold.redis.config.Config;
import com.lnold.redis.config.ConfigService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/config/api")
public class ConfigApiController {

    private final ConfigService configService;


    public ConfigApiController(ConfigService configService) {
        this.configService = configService;
    }

    @GetMapping("/")
    public ResponseEntity<List<Config>> getConfigList() {
        List<Config> configList = new ArrayList<>();
        Map<String, String> configs = configService.getAllConfigs();
        for (Map.Entry<String, String> entry : configs.entrySet()) {
            configList.add(new Config(entry.getKey(), entry.getValue()));
        }
        return ResponseEntity.ok(configList);
    }

    @PostMapping("/")
    public ResponseEntity<String> addConfig(@RequestBody Config config) {
        configService.setConfigValue(config.getKey(), config.getValue());
        configService.publishUpdate(config.getKey());
        return ResponseEntity.ok("配置已添加");
    }

    @PutMapping("/{name}")
    public ResponseEntity<String> editConfig(@PathVariable String name, @RequestBody Config config) {
        configService.setConfigValue(name, config.getValue());
        configService.publishUpdate(configService.getConfigValue(name));
        return ResponseEntity.ok("配置已编辑");
    }

    @DeleteMapping("/{name}")
    public ResponseEntity<String> deleteConfig(@PathVariable String name) {
        configService.deleteConfigValue(name);
        configService.publishUpdate(name);
        return ResponseEntity.ok("配置已删除");
    }

    @PostMapping("/import")
    public ResponseEntity<String> importConfig(@RequestParam("file") MultipartFile file) {
        try {
            File tempFile = File.createTempFile("temp-import", ".json");
            FileOutputStream fos = new FileOutputStream(tempFile);
            fos.write(file.getBytes());
            fos.close();

            configService.importConfig(tempFile);
            tempFile.delete();
            return ResponseEntity.ok("配置已导入");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("导入配置时发生错误");
        }
    }

    @GetMapping("/export")
    public void exportConfig(HttpServletResponse response) {
        try {
            String EXPORT_FILE_PATH = "config-export.json";
            File configFile = new File(EXPORT_FILE_PATH);
            configService.exportConfig(configFile);

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + configFile.getName());
            FileCopyUtils.copy(new FileReader(configFile), response.getWriter());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
